////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 www.iflytek.com. All Rights Reserved.
//  This software for customer relationship management system, developed by Iflytek_ZY team.
//  Software code and design for the team, copy rights reserved.
////////////////////////////////////////////////////////////////////////////////

package com.iflytek.ci.cums.controller;

import java.util.List;
import javax.validation.Valid;

import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.iflytek.ci.cums.domain.Account;
import com.iflytek.ci.cums.service.AccountService;
import com.iflytek.ci.cums.service.impl.EncryptionPassword;
import com.iflytek.ci.cums.service.impl.ShiroDbRealm;
import com.iflytek.ci.main.controller.BaseController;
import com.iflytek.ci.main.dto.Prior;
import com.iflytek.framework.pagination.PaginationCriteria;
import com.iflytek.framework.pagination.PaginationResult;
import com.iflytek.framework.web.messages.AjaxMessage;
import com.iflytek.framework.web.mvc.PaginationParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * .
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2012-10-27 11:43 AM
 * @since JDK 1.5
 */
@Controller
@RequestMapping("account/**")
public class AccountController extends BaseController {
	/** 序列化ID */
	private static final long serialVersionUID = -6172038073768403359L;
	/** 用户帐号服务 */
	@Autowired
	private AccountService accountService;

	// ~ href ////////////////////////////////////////////////////////////////

	/**
	 * 跳转到帐号管理首页
	 *
	 * @return 帐号管理首页地址
	 */
	@RequiresPermissions("Account:list")
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String load() {
		return "account/list";
	}

	/**
	 * 跳转到帐号管理首页
	 *
	 * @return 帐号管理首页地址
	 */
	@RequiresPermissions("Account:list")
	@RequestMapping(value = "tblist/{page_index}/{sort}/{order}", method = RequestMethod.GET)
	public String tb_load(@PathVariable int page_index, @PathVariable String sort, @PathVariable String order, Model model) {
		PaginationCriteria criteria = new PaginationCriteria((page_index - 1) * 15, 15, sort, StringUtils.equalsIgnoreCase("asc", order) ? PaginationCriteria.SortOrder.ASC : PaginationCriteria.SortOrder.DESC);
		logger.info("获取所有帐号信息");
		PaginationResult<Account> accounts = accountService.findAccounts(criteria);
		model.addAttribute("accounts", accounts);
		model.addAttribute("total",accounts.getTotal());
		return "account/list";
	}

	/**
	 * 跳转到新增页面
	 *
	 * @return 帐号管理新增帐号业务地址
	 */
	@RequiresPermissions("Account:edit")
	@RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
	public String add(@PathVariable long id, final Model model) {
		Account account = id == 0 ? new Account() : accountService.fromId(id);
		model.addAttribute("account", account);

		String roleList = "";
		if (account.getRoles() != null) {
			for (int i = 0; i < account.getRoles().size(); i++) {
				roleList += (i == account.getRoles().size() - 1) ? account
						.getRoles().get(i) : account
						.getRoles().get(i) + Prior.SEPARATE;
			}
		}
		model.addAttribute("roleList", roleList);
		return "account/edit";
	}

	/**
	 * 跳转到修改密码界面
	 *
	 * @return 修改密码界面
	 */
	@RequestMapping(value = "chpwd", method = RequestMethod.GET)
	public String link_chpwd() {
		return "account/password";
	}

	/**
	 * 跳转到个人信息界面
	 *
	 * @return 个人信息界面
	 */
	@RequestMapping(value = "profile", method = RequestMethod.GET)
	public String link_profile(final Model model) {
		// 获取当前登录人
		ShiroDbRealm.ShiroUser current_login_usr = (ShiroDbRealm.ShiroUser) SecurityUtils
				.getSubject().getPrincipal();
		// 从数据库中获取当前用户的信息
		final Account account = accountService
				.fromId(current_login_usr.getId());
		model.addAttribute("account", account);
		return "account/profile";
	}

	/**
	 * 修改密码
	 *
	 * @param oldpwd   旧密码
	 * @param password 新密码
	 * @return 修改后操作的提示
	 */
	@RequestMapping(value = "save_chpwd", method = RequestMethod.POST)
	@ResponseBody
	public AjaxMessage save_chpwd(
			@RequestParam(value = "oldpwd", required = true) String oldpwd,
			@RequestParam(value = "password", required = true) String password) {
		// 获取当前登录人
		ShiroDbRealm.ShiroUser current_login_usr = (ShiroDbRealm.ShiroUser) SecurityUtils
				.getSubject().getPrincipal();
		// 从数据库中获取当前用户的信息
		final Account account = accountService
				.fromId(current_login_usr.getId());
		String encry_pwd = EncryptionPassword.encryption(oldpwd);
		if (!StringUtils.equals(encry_pwd, account.getPassword())) {
			logger.info("wrong password");
			return ajax_error("您输入的旧密码不正确");
		} else if (StringUtils.equals(StringUtils.trim(password), "")) {
			logger.info("empty password");
			return ajax_error("对不起，您输入的密码为空，请重新输入");
		} else if (StringUtils.trim(password).length() < 6
				|| StringUtils.trim(password).length() > 16) {
			return ajax_error("对不起，密码长度应介于6-16位，请重新输入");
		} else {
			account.setPassword(EncryptionPassword.encryption(password));
			accountService.chpwd(account);
			logger.info("modify success");
			return ajax_info("密码修改成功");
		}

	}

	/**
	 * 保存一个新的帐号信息
	 * <p>
	 * SpringMVC中借助JSR303规范进行表单验证
	 * <li>第一步：在实体类中针对需要验证的属性，进行Annotation配置</li>
	 * <li>第二步：在Controller的方法参数前使用@Valid开启JSR303验证，并添加BindingResult参数</li>
	 * <li>BindingResult承载着JSR303验证时所产生的message，可据此进行判断验证结果</li>
	 * <li>第三步：判断BindingResult中是否装载了JSR303验证的message，有则转到前台页面显示出来</li>
	 * <li>第四步：前台页面中使用<form:errors path="username"/>打印JSR303的message信息</li>
	 * </p>
	 *
	 * @param account 帐号信息
	 * @return 成功后跳转到具体列表页面
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public AjaxMessage save(
			@Valid Account account,
			BindingResult result,
			@RequestParam(value = "user_roles", required = false) List<Integer> roleList) {
		// 该方法若有其它参数，应写成这样save(@Valid Account account, BindingResult result,
		// String abc)
		// 就是说，这里一定要把BindingResult放在待验证对象(@Valid Account account)参数的后面，否则会报错
		if (result.hasErrors()) {
			return ajax_error("保存失败!");
		}
		if (Objects.equal(account, null)) {
			return ajax_error("帐号信息不能为空");
		} else {
			account.setRoles(roleList);
			if (account.getId() == 0) {
				// 判断用户是否存在
				String log_name = account.getLogin();
				if (accountService.accountWithName(log_name) != null) {
					return ajax_error("账户已存在，请修改账户名");
				}
				// 新增
				// 12345为系统默认密码
				account.setPassword(EncryptionPassword.encryption("123456"));
				accountService.addAccount(account);
			} else {
				// 修改
				accountService.updateAccounts(account);
			}
		}
		return ajax_info("保存成功");
	}

	/**
	 * 删除1个或者多个帐号
	 *
	 * @param ids 帐号，以逗号分割
	 * @return 是否成功
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxMessage delete(String ids) {
		if (Strings.isNullOrEmpty(ids)) {
			return null;
		}
		String[] id_array = ids.split(Prior.SEPARATE);
		accountService.deleteAccount(id_array);
		return ajax_info("删除成功！");
	}

	/**
	 * 分页获取帐号信息
	 *
	 * @param criteria 分页参数信息
	 * @return 帐号信息
	 */
	@RequestMapping("list.json")
	@ResponseBody
	public PaginationResult<Account> allAccounts(
			@PaginationParam(required = false) PaginationCriteria criteria) {
		logger.info("获取所有帐号信息");
		return accountService.findAccounts(criteria);
	}

	@RequestMapping("fuzzy_search")
	@ResponseBody
	public PaginationResult<Account> fuzzy_search_account(
			@PaginationParam(required = false) PaginationCriteria criteria,
			String search) {
		logger.info("fuzzy_search with " + search);
		if (Strings.isNullOrEmpty(search)) {
			if (logger.isDebugEnabled()) {
				logger.debug("searche paramer is empty!");
			}
			search = "";
		}
		return accountService.fuzzy_search(criteria, search);
	}

	/**
	 * 导入用户请求
	 *
	 * @param attachment 上传的文件
	 * @return ajax请求
	 */
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public
	@ResponseBody
	AjaxMessage import_account(
			@RequestParam(value = "attachment") MultipartFile attachment) {
		if (!attachment.isEmpty()) {
			String file_name = attachment.getOriginalFilename();
			if (file_name.endsWith("xls")) {
				// 如果是excel
				accountService.import_account(attachment);
				return ajax_info("文件导入成功");
			} else {
				return ajax_warn("文件导入失败，请您上传Excel-2003或以下版本文件！");
			}
		} else {
			return ajax_error("请您上传Excel文件！");
		}
	}
}
